import { createStore, applyMiddleware, compose } from 'redux'
import { routerMiddleware } from 'react-router-redux'
import thunk from 'redux-thunk'

import loadingMiddleware from './middlewares/loadingMiddleware'
import promiseMiddleware from './middlewares/promiseMiddleware'
import errorMiddleware from './middlewares/errorMiddleware'
import api from './libs/api'

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose
export default (reducer, history, middlewares = []) => {
  const store = createStore(
    reducer,
    composeEnhancers(
      applyMiddleware(
        thunk.withExtraArgument(api),
        loadingMiddleware,
        promiseMiddleware,
        errorMiddleware,
        routerMiddleware(history),
        ...middlewares,
      ),
    ),
  )

  return store
}
